package com.telit.firecommand.controller;

import com.telit.common.entity.DataReturn;
import com.telit.common.enums.ResultCode;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.util.FileTypeCheckUtils;
import com.telit.firecommand.constant.FireConstant;
import com.telit.firecommand.listener.ExcelUtil;
import com.telit.firecommand.model.easyExcel.FirePointExcel;
import com.telit.firecommand.service.FirePointService;
import com.telit.firecommand.strategy.context.FirePersonStrategyContext;
import com.telit.firecommand.strategy.context.FireResourceStrategyContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;


/**
 * @Auther amy
 * @Describe 文件处理控制层
 */
@RestController
@RequestMapping("excel")
@Api(tags = "文件处理控制层")
@Slf4j
public class ExcelController {

    @Autowired
    private FirePointService firePointService;

    @Autowired
    private FireResourceStrategyContext fireResourceStrategyContext;

    @Autowired
    private FirePersonStrategyContext firePersonStrategyContext;

//    @GetMapping(value = "/template/fire-point", produces = "application/json;charset=UTF-8")
//    @ApiOperation("下载火烧迹地模板")
//    public void template(HttpServletResponse response) throws IOException {
//        response.setContentType("application/vnd.ms-excel");
//        response.setCharacterEncoding("utf-8");
//        String fileName = URLEncoder.encode("经纬度集合文件模板", "UTF-8");
//        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//        // 设置文件名
//        response.setHeader("filename", fileName + ".xlsx");
//        // 设置服务器headers白名单，可以让客户端进行访问操作的属性
//        response.setHeader("Access-Control-Expose-Headers", "filename");
//        EasyExcel.write(response.getOutputStream(), FirePointExcel.class).sheet(fileName).doWrite(
//                new ArrayList<FirePointExcel>());
//    }

//    @PostMapping(value = "/upload/fire-point", produces = "application/json;charset=UTF-8")
//    @ApiOperation("上传火烧迹地的经纬度文件")
//    public DataReturn upload(@RequestParam("file") MultipartFile file) throws IOException {
//        // 校验文件
//        if (file == null || file.getSize() == 0) {
//            return DataReturn.failure(ResultCode.BAD_REQUEST, "文件不能为空");
//        }
//        if (FileTypeCheckUtils.checkExcel(file.getOriginalFilename())) {
//            return DataReturn.failure(ResultCode.BAD_REQUEST.getCode(), "文件格式必须为excel格式,xls和xlsx后缀名结尾");
//        }
//
//        // 将数据包两层返回给到前端
//        List<List<String>> resultList = firePointService.getDataFormExcel(file);
//        List<List<List<String>>> secondList = new ArrayList<>();
//        secondList.add(resultList);
//        List<List<List<List<String>>>> threeList = new ArrayList<>();
//        threeList.add(secondList);
//
//        // 存储数据
////        fireLossService.saveFirePoint(fireId,JSON.toJSONString(threeList));
//        return DataReturn.ok(threeList);
//    }

    @PostMapping(value = "/uploadZip/fire-point", produces = "application/json;charset=UTF-8")
    @ApiOperation("上传火烧迹线zip包数据")
    public DataReturn uploadZip(@RequestParam("file") MultipartFile file) throws IOException {
        //校验参数
        if (file == null || file.getSize() == 0) {
            return DataReturn.failure(ResultCode.BAD_REQUEST, "文件不能为空");
        }
        if (FileTypeCheckUtils.checkZip(file.getOriginalFilename())) {
            return DataReturn.failure(ResultCode.BAD_REQUEST.getCode(), "文件格式必须为.zip文件");
        }

        List<String> list = firePointService.getDataFromZip(file);
        // 存入数据库
//        fireLossService.saveFirePoint(fireId,JSON.toJSONString(list));
        return DataReturn.ok(list);
    }

    /**
     * 对表格中的数据进行处理
     */
    public DataReturn saveList(@RequestParam("file") MultipartFile file) throws IOException {
        ExcelUtil.read(file.getInputStream(), FirePointExcel.class, 100, test()).sheet().doRead();
        return DataReturn.ok();
    }

    private Consumer<List<FirePointExcel>> test() {
        // listener里面doAfterAllAnalysed方法处理再此处写
        return lists -> System.out.println(lists.get(0));
    }

    /**
     * 根据名称在ftp服务器下载导入模板
     *
     * @param response
     * @param type
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/templateByType")
    @ApiOperation(value = "根据名称在ftp服务器下载导入模板")
    @ApiImplicitParam(name = "type", value = "模板名称", dataType = "String", paramType = "query")
    public DataReturn template(HttpServletResponse response, @RequestParam(value = "type") String type) {
        if (!FireConstant.RESOURCE_LIST.contains(type)) {
            return DataReturn.failure(ResultCode.BAD_REQUEST.getCode(), "模块参数不正确");
        }
        try {
            fireResourceStrategyContext.excelTemplate(type, response);
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.OPERATION_ERROR.getCode(), "下载模板失败");
        }
        return DataReturn.ok();
    }

    /**
     * 根据名称导入excel数据
     *
     * @param file
     * @param type
     *
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/importByType", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "根据名称导入excel数据")
    @ApiImplicitParam(name = "type", value = "需要导入数据的模块名称", dataType = "String", paramType = "query")
    public DataReturn importExcel(@RequestParam(value = "file") MultipartFile file,
                                  @RequestParam(value = "type") String type) {
        if (FileTypeCheckUtils.checkExcel(file.getOriginalFilename())) {
            return DataReturn.failure(ResultCode.BAD_REQUEST.getCode(), "文件格式必须为excel格式,xls和xlsx后缀名结尾");
        }
        if (!FireConstant.RESOURCE_LIST.contains(type)) {
            return DataReturn.failure(ResultCode.BAD_REQUEST.getCode(), "模块参数不正确");
        }
        try {
            fireResourceStrategyContext.excelImport(type, file);
            return DataReturn.ok();
        } catch (ForestBaseException e) {
            return DataReturn.failure(ResultCode.OPERATION_ERROR.getCode(), "导入数据失败,原因：" + e.getDefaultMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.OPERATION_ERROR);
        }
    }

    /**
     * 根据名称导出excel数据
     *
     * @param queryMap
     * @param type
     * @param response
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/exportByType")
    @ApiOperation(value = "根据名称导出excel数据")
    @ApiImplicitParam(name = "type", value = "需要导出数据的模块名称", dataType = "String", paramType = "query")
    public void exportExcel(@RequestParam(required = false) Map<String, Object> queryMap,
                            @RequestParam(value = "type") String type, HttpServletResponse response) {
        fireResourceStrategyContext.excelExport(type, queryMap, response);
//        return DataReturn.ok();
    }

    /**
     * 机构人员、扑火队人员导入excel数据
     *
     * @param file
     * @param type
     *
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/importPersonByType", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "根据名称导入excel数据")
    @ApiImplicitParam(name = "type", value = "需要导入数据的模块名称", dataType = "String", paramType = "query")
    public DataReturn importPersonByType(@RequestParam(value = "file") MultipartFile file,
                                         @RequestParam(value = "type") String type,
                                         @RequestParam(value = "id") Long id) {
        if (FileTypeCheckUtils.checkExcel(file.getOriginalFilename())) {
            return DataReturn.failure(ResultCode.BAD_REQUEST.getCode(), "文件格式必须为excel格式,xls和xlsx后缀名结尾");
        }
        if (!FireConstant.RESOURCE_LIST.contains(type)) {
            return DataReturn.failure(ResultCode.BAD_REQUEST.getCode(), "模块参数不正确");
        }
        try {
            firePersonStrategyContext.excelImportPerson(type, file, id);
            return DataReturn.ok();
        } catch (ForestBaseException e) {
            return DataReturn.failure(ResultCode.OPERATION_ERROR.getCode(), "导入数据失败,原因：" + e.getDefaultMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.OPERATION_ERROR);
        }
    }

}
